// ignore_for_file: non_constant_identifier_names
import 'dart:collection';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../common/app_manager.dart';
import '../widget/my_dialog.dart';
import 'dart:convert' as convert;

class ResultCode {
  static String loading = "loading"; // 请求中
  static String success = "20000"; // 请求成功
  static String empty_data = "20002"; // 请求成功,数据为空
  static String no_more_data = "20003"; // 请求成功,无更多数据
  static String resubmit = "20008"; // 重复提交
  static String error = "error"; //
  static String failure = "400";
  static String abnormal = "abnormal";
  static String token_null = "10005";
  static String uuid_null = "10302";
}

extension ResponseAnalyzedExt on ResponseAnalyzed {
  bool get notSuccess => code != '20000';
  bool get success => code == '20000';
  bool get empty => code == '20002';
  bool get noMoreData => code == '20003';
}

class ResponseAnalyzed {
  final String? code;
  late String? message;
  final dynamic data;
  late bool? isExposedToUser;
  final RequestOptions? request;

  show() => showMessage(message!);

  ResponseAnalyzed(
      {this.code,
      this.data,
      this.message,
      this.isExposedToUser = false,
      this.request});

  ResponseAnalyzed.loading() : code = ResultCode.loading, data = null, request = null;
  ResponseAnalyzed.empty() : code = ResultCode.empty_data, data = null, request = null;

  /*  解析服务器返回的json字典
    {"code":20000, "data": "购物车数据的json字典", "message": "请求成功"}
  */
  //factory ResponseAnalyzed.analyzing(Response response) {
  static _analyzing(Response response) {
    Map<dynamic, dynamic> jsonObject = convert.jsonDecode(response.toString());
    if (jsonObject.containsKey("code") && jsonObject.containsKey("data")) {
      var data = jsonObject['data'];
      return ResponseAnalyzed(
        code: jsonObject['code'].toString(),
        message: jsonObject['message'].toString(),
        data: data,
        request: response.requestOptions,
      );
    } else {
      return ResponseAnalyzed(
        code: '23456',
        message: '',
        data: '',
        request: response.requestOptions,
      );
    }
  }

  // 检查解析结果，进行统一处理
  // ResponseAnalyzed analyzingAndCheckup(Response response) {
  static Future<ResponseAnalyzed> analyzingAndCheckup(dynamic response) async {
    try {
      if (response is Response) {
        ResponseAnalyzed result = _analyzing(response);
        return _checkupResultCode(result);
      } else if (response is HashMap<String, dynamic>) {
        String? code = response['code'];
        String? msg = response['message'];
        ResponseAnalyzed result = ResponseAnalyzed(code: code, message: msg);
        return _checkupResultCode(result);
      } else {
        return ResponseAnalyzed(code: "$response", message: "$response");
      }
    } catch (e) {
      // showMessage('数据解析失败，请检查...');
      if (response != null) {
        // String? code = response.statusCode.toString();
        String? msg = response.statusMessage! + response.data.toString();
        ResponseAnalyzed result = ResponseAnalyzed(code: "23456", message: msg);
        return _checkupResultCode(result);
      }
      debugPrint("解析失败 e=$e");
      return ResponseAnalyzed(code: "$e", message: "$e");
    }
  }

// 检查解析结果，进行统一处理不同状态下的结果码
  static ResponseAnalyzed _checkupResultCode(ResponseAnalyzed result) {
    var code = int.parse(result.code!);
    if (code == 20002 || code == 20003 || code == 27106 || (code == 29999 && result.message == "无更多数据")) {
      result.message = '';
    } else if (code == 20401) {
      AppManager.signOut();
    } else if (code > 20000 && code < 30000) {
      debugPrint('code: $code, message: ${result.message!}');
      result.isExposedToUser = true;
      showMessage(result.message!);
      debugPrint("result.message! = ${result.message!}");
    } else if (code >= 10000 && code <= 19999) {
      // 上传错误日志
      Map par = {
        "code": result.code,
        "message": result.message,
        "data": result.data
      };
      showFailureMessage("$code 系统发生错误，请联系管理员");
      _uploadErrorLogWithResponse(convert.jsonEncode(par));
    } else if (code == 1000) {
      result = ResponseAnalyzed(code: "error", data: "", message: result.message);
      showMessage(result.message!);
    }
    return result;
  }

  // todo: 上传错误日志
  static Future _uploadErrorLogWithResponse(String response) async {
    // 异常错误，需要上报服务器，方便排查错误
    // debugPrint('uploadErrorLogWithResponse = $response');
    // LSLog(@"%@", result.request.HTTPBody);
    // result.request.baseUrl
  }
}

// 检查解析结果，进行统一处理
ResponseAnalyzed analyzingAndCheckup(dynamic response) {
  try {
    if (response is Response) {
      ResponseAnalyzed result = ResponseAnalyzed._analyzing(response);
      ResponseAnalyzed._checkupResultCode(result);
      return result;
    } else if (response is HashMap<String, dynamic>) {
      String? code = response['code'];
      String? msg = response['message'];
      ResponseAnalyzed result = ResponseAnalyzed(code: code, message: msg);
      ResponseAnalyzed._checkupResultCode(result);
      return result;
    } else {
      debugPrint("response = $response");
      return ResponseAnalyzed(code: "error", message: response["message"]);
    }
  } catch (e) {
    //showMessage('数据解析失败，请检查...');
    String? code = response.statusCode.toString();
    String? msg = response.statusMessage! + response.data.toString();
    ResponseAnalyzed result = ResponseAnalyzed(code: "23456", message: msg);
    ResponseAnalyzed._checkupResultCode(result);
    return result;
  }
}
